package sqlite_conf_table

import (
	"database/sql"
	"errors"
	"fmt"
	"github.com/duke-git/lancet/v2/strutil"
	_ "github.com/mattn/go-sqlite3"
	"github.com/sirupsen/logrus"
	"go-iot-gateway/internal/apk/files"
	"go-iot-gateway/internal/apk/sqlites"
	sys_config "go-iot-gateway/internal/sys/config"
	"os"
	"strings"
)

func LoadConfig(homeDir string, configInfo sys_config.ConfigTableEnv) error {
	//文件路径初始化
	if configInfo.Type != "sql" {
		return errors.New("未知的存储类型 " + configInfo.Type)
	}

	//数据库url 获取
	datasourceUrl := configInfo.Datasource.Url
	if strings.TrimSpace(datasourceUrl) == "" {
		configPath := configInfo.Path
		if strutil.IsBlank(configPath) {
			configPath = homeDir + string(os.PathSeparator) + "config" // 默认路径
		}
		realConfigPath, err := files.Mkdir(configPath)
		if err != nil {
			panic(err)
		}
		realConfigPath = realConfigPath + string(os.PathSeparator)
		datasourceUrl = "jdbc:sqlite:" + realConfigPath + "sqlite.db"
	}

	path, err := sqlites.GetSqlitePath(datasourceUrl)
	if err != nil {
		return err
	}
	fmt.Println("典表配置路径 :" + path)
	database, err := sql.Open("sqlite3", path)
	if err != nil {
		return err
	}

	//只加载一次数据，然后就释放连接
	defer func() {
		err := database.Close()
		if err != nil {
			logrus.Warn("配置库关闭失败")
		}
	}()

	//加载数据
	err = selectProtocolConfInfo(database)
	if err != nil {
		return err
	}
	err = selectChannelInfo(database)
	if err != nil {
		return err
	}
	err = selectDeviceConfInfo(database)
	if err != nil {
		return err
	}
	err = selectTagAssist(database)
	if err != nil {
		return err
	}
	err = selectTagInfo(database)
	if err != nil {
		return err
	}
	err = selectScriptConfInfo(database)
	if err != nil {
		return err
	}
	err = selectFormulaConfInfo(database)
	if err != nil {
		return err
	}
	return nil
}
